#!/bin/sh
# tlp-rdw - handle dock/undock events
#
# Copyright (c) 2024 Thomas Koch <linrunner at gmx.net> and others.
# SPDX-License-Identifier: GPL-2.0-or-later

# --- Source libraries

for lib in @TLP_TLIB@/tlp-func-base @TLP_FLIB@/25-tlp-func-rf @TLP_FLIB@/30-tlp-func-rf-sw; do
        # shellcheck disable=SC1090
    . "$lib" || exit 70
done

# --- MAIN

# read configuration: quit on error, trace allowed
read_config 1 0

check_tlp_enabled || do_exit 0
check_run_flag "$RDW_KILL" && do_exit 0
add_sbin2path

# get power source
get_sys_power_supply

# get device/type
ddev=/sys$1
devtype=$2

case $devtype in
    dock)
        # check if type is "dock_station", quit if not
        type=$(read_sysf "$ddev/type")
        [ "$type" = "dock_station" ] || do_exit 0

        docked=$(read_sysf "$ddev/docked")
        action=$EVENT

        # shellcheck disable=SC2154
        echo_debug "udev" "+++ rdw_udev($devtype).$action dev=$ddev type=$type docked=$docked syspwr=$_syspwr"
        ;;

    usb_dock)
        # shellcheck disable=SC2153
        case $ACTION in
            add)    action="dock"  ;;
            remove) action="undock"  ;;
        esac

        echo_debug "udev" "+++ rdw_udev($devtype).$action dev=$ddev syspwr=$_syspwr"
        ;;

    *) do_exit 0 ;; # unknown device type
esac

# quit if timed lock in progress
if check_timed_lock "$RDW_DOCK_LOCK" ; then
    echo_debug "udev" "rdw_udev.locked"
    do_exit 0
fi

case $action in
    dock) # laptop was docked

        # lock for 2 seconds in case dock has multiple devices
        set_timed_lock "$RDW_DOCK_LOCK" "$RDW_NM_LOCKTIME"

        # enable configured radios (obey rdw nm locks too)
        for dev in $DEVICES_TO_ENABLE_ON_DOCK; do
            [ -n "$dev" ] && ! check_timed_lock "${RDW_NM_LOCK}_${dev}" \
                && device_switch "$dev" on "${RDW_NM_LOCK}_${dev}" "$RDW_NM_LOCKTIME"
        done

        # disable configured radios (obey rdw nm locks too)
        for dev in $DEVICES_TO_DISABLE_ON_DOCK; do
            [ -n "$dev" ] && ! check_timed_lock "${RDW_NM_LOCK}_${dev}" \
                && device_switch "$dev" off "${RDW_NM_LOCK}_${dev}" "$RDW_NM_LOCKTIME"
        done
        ;;

    undock) # laptop was undocked

        # lock for 2 seconds in case dock has multiple devices
        set_timed_lock "$RDW_DOCK_LOCK" "$RDW_NM_LOCKTIME"

        # enable configured radios (obey rdw nm locks too)
        for dev in $DEVICES_TO_ENABLE_ON_UNDOCK; do
            [ -n "$dev" ] && ! check_timed_lock "${RDW_NM_LOCK}_${dev}" \
                && device_switch "$dev" on "${RDW_NM_LOCK}_${dev}" "$RDW_NM_LOCKTIME"
        done

        # disable configured radios (obey rdw nm locks too)
        for dev in $DEVICES_TO_DISABLE_ON_UNDOCK; do
            [ -n "$dev" ] && ! check_timed_lock "${RDW_NM_LOCK}_${dev}" \
                && device_switch "$dev" off "${RDW_NM_LOCK}_${dev}" "$RDW_NM_LOCKTIME"
        done
        ;;

    *) ;; # unknown action -> do nothing
esac

do_exit 0
